#include "connection.h"

#include "log.h"

namespace chat {
bool Connection::insert(const server_t::connection_ptr& conn,
                        const ClientPtr client) {
    std::lock_guard<std::mutex> lock(mutex_);

    uid_conn_map[client->user_id] = conn;
    conn_client_map[conn] = client;

    LOG_DEBUG("长连接建立成功: [{}]: {}-{}", static_cast<void*>(conn.get()),
              client->user_id, client->session_id);

    return true;
}

server_t::connection_ptr Connection::connection(const std::string& user_id) {
    std::lock_guard<std::mutex> lock(mutex_);

    auto it = uid_conn_map.find(user_id);
    if (it != uid_conn_map.end()) {
        return it->second;
    }

    LOG_ERROR("未找到客户端{} 对应的长连接", user_id);

    return nullptr;
}

ClientPtr Connection::client(const server_t::connection_ptr& conn) {
    std::lock_guard<std::mutex> lock(mutex_);
    auto it = conn_client_map.find(conn);
    if (it != conn_client_map.end()) {
        return it->second;
    }

    LOG_ERROR("未找到长连接{} 对应的客户端", static_cast<void*>(conn.get()));

    return nullptr;
}

bool Connection::remove(const server_t::connection_ptr& conn) {
    std::lock_guard<std::mutex> lock(mutex_);

    auto it = conn_client_map.find(conn);
    if (it != conn_client_map.end()) {
        conn_client_map.erase(it);
        uid_conn_map.erase(it->second->user_id);
        return true;
    }

    LOG_ERROR("未找到长连接{} 对应的客户端", static_cast<void*>(conn.get()));

    return false;
}
}  // namespace chat